﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Metal_Archives
{
    public partial class Album : PhoneApplicationPage
    {
        CommonMethods cm = new CommonMethods();
        string name;
        string link;
        string color;

        public Album()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            //Don't do anything if you're returning to the page
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                name = this.NavigationContext.QueryString["name"];
                link = this.NavigationContext.QueryString["link"];
                this.sunroof.Title = name.ToLower();

                //Need to hide the color of the selected item, but need black or white depending on OS theme choice
                color = cm.themeFontColor();

                //Is the user connected to the internet?
                if (cm.isOnline())
                {
                    //Get data from site
                    WebClient wc = new WebClient();
                    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
                    wc.DownloadStringAsync(new Uri(link));
                }
            }
            else
            {
                this.lsbSongs.SelectedIndex = -1;
                this.lsbLineup.SelectedIndex = -1;
            }
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (cm.isOnlineE(e))
            {
                HtmlAgilityPack.HtmlDocument bandHTML = new HtmlAgilityPack.HtmlDocument();
                bandHTML.LoadHtml(e.Result);

                //Load each pivot page's info
                Album_About(bandHTML);
                Album_Songs(bandHTML);
                Album_Cover(bandHTML);
                Album_Lineup(bandHTML);
                Album_Reviews(bandHTML);
                Album_Notes(bandHTML);

                //Is the user connected to the internet?
                if (cm.isOnline())
                {
                    //Misc
                    WebClient wcDiscogMisc = new WebClient();
                    Uri discogMiscURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/misc");
                    //wcDiscogMisc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
                    wcDiscogMisc.DownloadStringAsync(discogMiscURI, discogMiscURI);

                    //Related Links
                    WebClient wcRelatedLinks = new WebClient();
                    //wcRelatedLinks.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_RelatedLinks);
                    wcRelatedLinks.DownloadStringAsync(new Uri("http://www.metal-archives.com/link/ajax-list/type/band/id/" + link.Substring(link.LastIndexOf("/") + 1)));
                }
            }
        }

        public void Album_About(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            string leftBandInfo = bandHTML.DocumentNode.Descendants("dl").First(x => x.InnerText.Contains("Type")).InnerHtml;
            string rightBandInfo = bandHTML.DocumentNode.Descendants("dl").First(x => x.InnerText.Contains("Label")).InnerHtml;

            //Top info
            string albumName, bandName;
            //Left info
            string type, releaseDate;
            //Right info
            string label, reviews;

            //split up top band info
            albumName = bandHTML.DocumentNode.Descendants("h1").First().InnerText;
            bandName = bandHTML.DocumentNode.Descendants("h2").First().InnerText;


            //Split up leftBandInfo
            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd>") + 4);

            type = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));

            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd>") + 4);

            releaseDate = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));


            //Split up rightBandInfo
            rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf("<dd>") + 4);
            if (rightBandInfo.StartsWith("<a"))
            {
                rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf(">") + 1);
            }

            label = rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));

            rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf("<dd>") + 4);

            if (!rightBandInfo.Substring(0, rightBandInfo.IndexOf("<")).Contains("None yet"))
            {
                reviews = rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));

                rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf(">") + 1);

                reviews += rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));

                rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf(">") + 1);

                reviews += rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));
                reviews = reviews.Trim();
            }
            else
            {
                reviews = "None yet";
            }


            //Fill in TextBlock
            List<Links> linksInCat = new List<Links>();
            linksInCat.Add(new Links("album name:", "", color, albumName));
            linksInCat.Add(new Links("band name:", "", color, bandName));
            linksInCat.Add(new Links("type:", "", color, type));
            linksInCat.Add(new Links("release date:", "", color, releaseDate));
            linksInCat.Add(new Links("label:", "", color, label));
            linksInCat.Add(new Links("reviews:", "", color, reviews));
            this.lsbAbout.ItemsSource = linksInCat;
        }

        public void Album_Songs(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            List<Links> lsbSongsDataSource = new List<Links>();
            string ddSongsHTML = bandHTML.DocumentNode.Descendants("tbody").First().InnerHtml;

            while (ddSongsHTML.Contains("<tr"))
            {
                ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("<tr") + 3);
                if (ddSongsHTML.Contains("<tr"))
                {
                    ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("</a>") + 4);

                    string linkName = ddSongsHTML.Substring(0, ddSongsHTML.IndexOf("</td"));

                    ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("<td>") + 4);

                    linkName += " " + ddSongsHTML.Substring(0, ddSongsHTML.IndexOf("</td")).Trim();

                    ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("<td"));
                    ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf(">") + 1);

                    string linkDesc = ddSongsHTML.Substring(0, ddSongsHTML.IndexOf("</td"));

                    string linkPath;
                    if (ddSongsHTML.Substring(0, ddSongsHTML.IndexOf("</tr>")).Contains("Show lyrics"))
                    {
                        ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("href") + 6);

                        linkPath = ddSongsHTML.Substring(0, ddSongsHTML.IndexOf("\""));
                    }
                    else
                    {
                        linkPath = "";
                    }

                    ddSongsHTML = ddSongsHTML.Substring(ddSongsHTML.IndexOf("<tr") + 3);

                    lsbSongsDataSource.Add(new Links(linkName, linkPath, color, linkDesc));
                }
                else
                {
                    break;
                }
            }

            this.lsbSongs.ItemsSource = lsbSongsDataSource;
        }

        private void lsbSongs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Links selected = (sender as ListBox).SelectedItem as Links;
            if (selected.linkPath.Length > 0)
            {
                NavigationService.Navigate(new Uri(
                        "/Song.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                        , UriKind.Relative));
            }
        }

        public void Album_Cover(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            string coverURL = "";
            try
            {
                string cover = bandHTML.DocumentNode.Descendants("a").First(x => x.Id == "cover").InnerHtml;
                coverURL = cover.Substring(
                    cover.IndexOf("\"") + 1,
                    cover.Substring(cover.IndexOf("\"") + 1).IndexOf("\"")
                );
            }
            catch { }

            string imageHTML = "<HTML><HEAD><META NAME=\"viewport\" CONTENT=\"WIDTH=420\" ID=\"viewport\" /></HEAD>" +
                "<BODY BGCOLOR=\"#000000\">";
            if (coverURL.Length > 0) { imageHTML += "<IMG SRC=\"" + coverURL + "\">"; }
            imageHTML += "</body></html>";

            wbCover.NavigateToString(imageHTML);
        }

        public void Album_Lineup(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            List<LinkCats> ddLineupDataSource = new List<LinkCats>();
            string ddLineupHTML = bandHTML.DocumentNode.Descendants("div").Last(x => x.Id == "album_members").InnerHtml;

            while (ddLineupHTML.Contains("<li>"))
            {
                ddLineupHTML = ddLineupHTML.Substring(ddLineupHTML.IndexOf("<li>") + 4);
                ddLineupHTML = ddLineupHTML.Substring(ddLineupHTML.IndexOf("href") + 7);

                string linkCatAnchor = ddLineupHTML.Substring(0, ddLineupHTML.IndexOf("\""));

                ddLineupHTML = ddLineupHTML.Substring(ddLineupHTML.IndexOf(">") + 1);

                string linkCatName = ddLineupHTML.Substring(0, ddLineupHTML.IndexOf("</")).ToLower();

                List<Links> linksInCat = new List<Links>();
                string linksInCatHTML = bandHTML.DocumentNode.Descendants("div").First(x => x.Id == linkCatAnchor).InnerHtml;

                while (linksInCatHTML.Contains("<tr"))
                {
                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("<tr") + 3);
                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("href") + 6);

                    string linkPath = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("\""));

                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf(">") + 1);

                    string linkName = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("</a"));

                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("<td") + 4);

                    string linkDesc = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("</td")).Trim();
                    linkDesc = linkDesc.Replace("&quot;", "\"");

                    linksInCat.Add(new Links(linkName, linkPath, color, linkDesc));
                }

                if (!linkCatName.ToLower().Contains("complete"))
                {
                    ddLineupDataSource.Add(new LinkCats(linkCatName, linkCatAnchor, linksInCat));
                }
            }

            this.ddLineup.ItemsSource = ddLineupDataSource;
            this.lsbLineup.ItemsSource = ddLineupDataSource[0].linksInCat;
        }

        private void ddLineup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListPicker).SelectedIndex >= 0)
            {
                lsbLineup.ItemsSource = ((sender as ListPicker).SelectedItem as LinkCats).linksInCat;
            }
        }

        private void lsbLineup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                NavigationService.Navigate(new Uri(
                    "/Artist.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                    , UriKind.Relative));
            }
        }

        public void Album_Reviews(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            List<Links> ddReviewsDataSource = new List<Links>();

            try
            {
                string ddReviewsHTML = bandHTML.DocumentNode.Descendants("table").First(x => x.Id == "review_list").InnerHtml;

                while (ddReviewsHTML.Contains("<tr"))
                {
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<tr") + 3);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("href") + 6);

                    string linkPath = ddReviewsHTML.Substring(0, ddReviewsHTML.IndexOf("\""));

                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<td") + 1);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<td") + 1);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf(">") + 1);

                    string linkDesc = "score: " + ddReviewsHTML.Substring(0, ddReviewsHTML.IndexOf("</td"));

                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<td") + 1);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<a") + 1);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf(">") + 1);

                    string linkName = ddReviewsHTML.Substring(0, ddReviewsHTML.IndexOf("</a"));

                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf("<td") + 1);
                    ddReviewsHTML = ddReviewsHTML.Substring(ddReviewsHTML.IndexOf(">") + 1);

                    linkDesc += "\ndate: " + ddReviewsHTML.Substring(0, ddReviewsHTML.IndexOf("</td"));

                    ddReviewsDataSource.Add(new Links(linkName, linkPath, color, linkDesc));
                }
            }
            catch
            {
                ddReviewsDataSource.Add(new Links("There are no reviews for this album yet.", "", color));
            }

            this.lsbReviews.ItemsSource = ddReviewsDataSource;
        }

        private void lsbReviews_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                if (selected.linkPath.Length > 0)
                {
                    NavigationService.Navigate(new Uri(
                                "/Review.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                                , UriKind.Relative));
                }
            }
        }

        public void Album_Notes(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            try
            {
                this.lblNotes.Text = bandHTML.DocumentNode.Descendants("div").First(x => x.Id == "album_tabs_notes").InnerText.Trim();
            }
            catch { }
            if (cm.isThemedark()) { this.lblNotes.Foreground = new SolidColorBrush(Colors.White); }
            else { this.lblNotes.Foreground = new SolidColorBrush(Colors.Black); }
        }
    }
}